<?php

class GalleryController extends AdminController {

    private $separator = '{$$$}';
    public $disableScripts = array();

    const ALBUM_CLASS_NAME = 'Album';
    const PHOTO_CLASS_NAME = 'Photo';

    private $photoActions = array('photostatus', 'createphoto', 'updatephoto', 'deletephoto');

    /**
     * Check "Is current action a action which is invoked Photo Model?"
     * @return bool return TRUE if it is, else return false 
     */
    private function isActionOfPhoto() {
	$lowerCaseAction = strtolower($this->action->id);
	return in_array($lowerCaseAction, $this->photoActions) ? TRUE : FALSE;
    }

    public function actionIndex() {
	$model = new Album("search");
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET[self::ALBUM_CLASS_NAME])) {
	    $model->attributes = $_GET[self::ALBUM_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::ALBUM_CLASS_NAME, $_GET[self::ALBUM_CLASS_NAME]);
	} else if (isset($_POST[self::ALBUM_CLASS_NAME])) {
	    $model->attributes = $_POST[self::ALBUM_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::ALBUM_CLASS_NAME, $_POST[self::ALBUM_CLASS_NAME]);
	} else {
	    $articleState = Yii::app()->user->getState(app()->controller->id . self::ALBUM_CLASS_NAME);
	    if ($articleState != null)
		$model->attributes = $articleState;
	}

	$this->render('index', array(
	    'model' => $model,
	));
    }

    public function actionRefresh() {
	Yii::app()->user->setState(app()->controller->id . self::ALBUM_CLASS_NAME, null);
	$this->redirect(url(app()->controller->id . "/index"));
    }

    /**
     * Clear data session of Photo list
     * @param type $id
     */
    public function actionDetailRefresh($id) {
	Yii::app()->user->setState(app()->controller->id . self::PHOTO_CLASS_NAME, null);
	$this->redirect(url(app()->controller->id . "/detail/" . $id));
    }

    function actions() {
	return array(
	    'deleteAlbum' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'ajaxView' => "//share/_delete",
		'validateMethod' => 'validateDelete',
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))))
	    ),
	    'deletePhoto' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'ajaxView' => "//share/_delete",
		'view' => "//share/_delete",
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_PHOTO', 'gallery'))))
	    ),
	    'status' => array(
		'class' => 'lib.components.actions.LGActiveItemAction',
		'modelClass' => self::ALBUM_CLASS_NAME,
		'itemName' => t('LBL_ALBUM', 'gallery'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))))
	    ),
	    'photoStatus' => array(
		'class' => 'lib.components.actions.LGActiveItemAction',
		'modelClass' => self::PHOTO_CLASS_NAME,
		'itemName' => t('LBL_PHOTO', 'gallery'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_PHOTO', 'gallery'))))
	    ),
//	    'createAlbum' => array(
//		'class' => 'lib.components.actions.CreateAction',
//		'modelClass' => self::ALBUM_CLASS_NAME,
//		'ajaxView' => '_form',
//		'customAction' => 'createAlbum',
//		'messages' => array('success' => t('MSG_INSERT_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))))
//	    ),
	);
    }

    public function stopJS() {
	$defaultDisableScripts = array(
	    'jquery.js',
	    'jquery.min.js',
	    'jquery-ui.min.js'
	);

	// Merge with user set scripts which should be disabled
	if (is_array($this->disableScripts)) {
	    $this->disableScripts = CMap::mergeArray(
			    $defaultDisableScripts, $this->disableScripts);
	}
	else
	    throw new CException(Yii::t($this->tCategory, t('MSG_DISABLE_SCRIPT', 'messages')));

	// Disable scripts
	foreach ($this->disableScripts as $script)
	    Yii::app()->clientScript->scriptMap[$script] = false;
    }

    public function actionCreateAlbum() {
	$this->stopJS();
	$model = new Album('create');

	if (isset($_POST[self::ALBUM_CLASS_NAME])) {
	    $model->attributes = $_POST[self::ALBUM_CLASS_NAME];
	    $fileUpload = $_FILES[self::ALBUM_CLASS_NAME];
	    $oldPicture = $model->picture;

	    if ($fileUpload['size']['picture'] > 0) {
		$newName = gmdate('YmdGis') . '_' . stringSafeFile($fileUpload['name']['picture']);
		$model->picture = $newName;
	    }
	    // Save only if model validates
	    if ($model->validate()) {
		if ($fileUpload['size']['picture'] > 0) {
		    if ($model->save()) {
			move_uploaded_file($fileUpload['tmp_name']['picture'], GALLERY_FOLDER . $newName);
			$this->renderMessage('success', t('MSG_INFO_CREATE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))));
		    }
		}
	    } else {
		$model->picture = $oldPicture;
	    }
	}

	$this->renderMessage('render', $this->renderPartial('_form', array('model' => $model), true, true));
    }

//    public function createAlbum() {
//	$this->stopJS();
//	$model = new Album('create');
//
//	if (isset($_POST[self::ALBUM_CLASS_NAME])) {
//	    $model->attributes = $_POST[self::ALBUM_CLASS_NAME];
//	    $fileUpload = $_FILES[self::ALBUM_CLASS_NAME];
//	    $oldPicture = $model->picture;
//
//	    if ($fileUpload['size']['picture'] > 0) {
//		$newName = gmdate('YmdGis') . '_' . stringSafeFile($fileUpload['name']['picture']);
//		$model->picture = $newName;
//	    }
//	    // Save only if model validates
//	    if ($model->validate()) {
//		if ($fileUpload['size']['picture'] > 0) {
//		    if ($model->save()) {
//			move_uploaded_file($fileUpload['tmp_name']['picture'], GALLERY_FOLDER . $newName);
//			$this->renderMessage('success', 'Album has been created successful');
//		    }
//		}
//	    } else {
//		$model->picture = $oldPicture;
//	    }
//	}
//
//	$this->renderMessage('render', $this->renderPartial('_form', array('model' => $model), true, true));
//    }

    public function actionCreatePhoto($album_id) {
	$this->stopJS();
	$model = new Photo('create');

	$articleState = Yii::app()->user->getState(app()->controller->id . self::PHOTO_CLASS_NAME);

	if (isset($articleState['album_id'])) {
	    $model->album_id = $articleState['album_id'];
	} else {
	    $model->album_id = $album_id;
	}

	if (isset($_POST[self::PHOTO_CLASS_NAME])) {
	    $model->attributes = $_POST[self::PHOTO_CLASS_NAME];
	    $fileUpload = $_FILES[self::PHOTO_CLASS_NAME];
	    $oldPicture = $model->picture;

	    if ($fileUpload['size']['picture'] > 0) {
		$newName = gmdate('YmdGis') . '_' . stringSafeFile($fileUpload['name']['picture']);
		$model->picture = $newName;
	    }

	    // Save only if model validates
	    if ($model->validate()) {
		if ($fileUpload['size']['picture'] > 0) {
		    if ($model->save()) {
			move_uploaded_file($fileUpload['tmp_name']['picture'], GALLERY_FOLDER . $newName);
			$this->renderMessage('success', t('MSG_INFO_CREATE_SUCCESS', 'messages', array('{0}' => t('LBL_PHOTO', 'gallery'))));
		    }
		}
	    } else {
		$model->picture = $oldPicture;
	    }
	}
	$this->renderMessage('render', $this->renderPartial('_formphoto', array('model' => $model), true, true));
    }

    public function actionUpdateAlbum($id) {
	$this->stopJS();

	$model = Album::model()->findByPk($id);

	if ($model == null) {
	    //Must throw CHttpException, If not, when ajax request, error will not run errorHandler
	    //Must return 200 to client recieve this error
	    //throw new CHttpException(200, Yii::t('messages', '404'));
	    $this->renderMessage(MsgType::ERROR, Yii::t('messages', '404'));
	    app()->end();
	}

	$oldName = $model->picture;
	if (isset($_POST[self::ALBUM_CLASS_NAME])) {
	    $model->attributes = $_POST[self::ALBUM_CLASS_NAME];
	    $fileUpload = $_FILES[self::ALBUM_CLASS_NAME];

	    if ($fileUpload['size']['picture'] > 0) {
		//If user uploads new picture
		$newName = gmdate('YmdGis') . '_' . stringSafeFile($fileUpload["name"]["picture"]);
		$model->picture = $newName;
	    } else {
		//If user doesn't upload new picture, keep old file
		$model->picture = $oldName;
	    }

	    if ($model->validate()) {
		if ($fileUpload['size']['picture'] > 0) {
		    $oldPath = GALLERY_FOLDER . $oldName;
		    if ($model->update()) {

			//deletes old file if user uploads new file
			if (file_exists($oldPath)) {
			    unlink($oldPath);
			}

			//creates new picture file
			move_uploaded_file($fileUpload['tmp_name']['picture'], GALLERY_FOLDER . $newName);
			$this->renderMessage('success', t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))));
		    }
		} else {
		    $model->update();
		    $this->renderMessage('success', t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ALBUM', 'gallery'))));
		}
	    } else {
		$model->picture = $oldName;
	    }
	}
	$this->renderMessage('render', $this->renderPartial('_form', array('model' => $model), true, true));
    }

    public function actionUpdatePhoto($id) {

	$this->stopJS();

	$model = Photo::model()->findByPk($id);

	if ($model == null) {
	    //Must throw CHttpException, If not, when ajax request, error will not run errorHandler
	    //Must return 200 to client recieve this error
	    //throw new CHttpException(200, Yii::t('messages', '404'));
	    $this->renderMessage(MsgType::ERROR, Yii::t('messages', '404'));
	    app()->end();
	}

	$oldName = $model->picture;

	if (isset($_POST[self::PHOTO_CLASS_NAME])) {
	    $model->attributes = $_POST[self::PHOTO_CLASS_NAME];
	    $fileUpload = $_FILES[self::PHOTO_CLASS_NAME];

	    if ($fileUpload['size']['picture'] > 0) {
		//If user uploads new picture
		$newName = gmdate('YmdGis') . '_' . stringSafeFile($fileUpload["name"]["picture"]);
		$model->picture = $newName;
	    } else {
		//If user doesn't upload new picture, keep old file
		$model->picture = $oldName;
	    }

	    if ($model->validate()) {
		if ($fileUpload['size']['picture'] > 0) {
		    $oldPath = GALLERY_FOLDER . $oldName;

		    if ($model->update()) {

			//deletes old file if user uploads new file
			if (file_exists($oldPath)) {
			    unlink($oldPath);
			}

			//creates new picture file
			move_uploaded_file($fileUpload['tmp_name']['picture'], GALLERY_FOLDER . $newName);
			$this->renderMessage('success', t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_PHOTO', 'gallery'))));
		    }
		} else {
		    $model->update();
		    $this->renderMessage('success', t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_PHOTO', 'gallery'))));
		}
	    } else {
		$model->picture = $oldName;
	    }
	} else {
	    if (!Yii::app()->request->isAjaxRequest) {
		throw new CHttpException(403, 'Only post and ajax requests are allowed');
	    }
	}
	$this->renderMessage('render', $this->renderPartial('_formphoto', array('model' => $model), true, true));
    }

//
//    public function actionStatus($id) {
//	if (Yii::app()->request->isAjaxRequest) {
//	    if ($id != '') {
//		$album = Album::model()->findByPk($id);
//
//		$album->status = ($album->status == 1 ? 0 : 1);
//		if ($album->save()) {
//		    exit;
//		}
//	    }
//	}
//    }
//
//    public function actionPhotoStatus($id) {
//	if (Yii::app()->request->isAjaxRequest) {
//	    if ($id != '') {
//		$photo = Photo::model()->findByPk($id);
//
//		$photo->status = ($photo->status == 1 ? 0 : 1);
//		if ($photo->save()) {
//		    exit;
//		}
//	    }
//	}
//    }

    public function actionDetail($id) {
	$model = new Photo();
	$model->unsetAttributes();

	if (isset($_GET[self::PHOTO_CLASS_NAME])) {
	    $model->attributes = $_GET[self::PHOTO_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::PHOTO_CLASS_NAME, $_GET[self::PHOTO_CLASS_NAME]);
	} else {
	    //Load session data
	    $articleState = Yii::app()->user->getState(app()->controller->id . self::PHOTO_CLASS_NAME);

	    if ($articleState != null) {
		$model->attributes = $articleState;
	    }

	    //If dont have session data, set $model->album_id
	    if (!isset($model->album_id)) {
		$model->album_id = $id;
	    }
	}

	$album = Album::model()->findByPk($id);
	$this->render('detail', array('model' => $model, 'album' => $album));
    }

    public function loadModel() {
	$model = null;
	$isCreatePhoto = $this->isActionOfPhoto();
	if (isset($_GET['id'])) {
	    $ids = explode(',', $_GET['id']);
	    if (isset($ids)) {
		$criteria = new CDbCriteria;
		$criteria->addInCondition('id', $ids);
		if ($isCreatePhoto) {
		    $model = Photo::model()->findAll($criteria);
		}
		else
		    $model = Album::model()->findAll($criteria);
	    }
	}
	return $model;
    }

    public function validateDelete($model) {
	$ids = explode(',', $_GET['id']);
	$msg = NULL;

	$isCreatePhoto = $this->isActionOfPhoto();

	if (!$isCreatePhoto) {
	    foreach ($ids as $id) {
		$album = Album::model()->findByPk($id);

		if ($album == null) {
		    $msg = new LGMessage(MsgType::ERROR, t('404', 'messages'));
		} else {

		    $count = $album->countPhoto();
		    if ($count > 0) {
			$msg = new LGMessage(MsgType::ERROR, t('MSG_ERROR_DELETE_UNSUCCESS', 'messages'));
			return $msg;
		    }
		}
	    }
	}
	return $msg;
    }

    public function renderMessage($status, $content) {
	echo $status . $this->separator . $content;
	Yii::app()->end();
    }

    /**
     * 
     * @param Album $albumModel
     * @return type
     */
    public function getHtmlUpButtonForAlbum($albumModel) {

	$html = '';
	if ($albumModel->previousAlbumID != NULL) {
	    $actionParam = '?action=' . $albumModel->previousAlbumID;
	    $actionClassName = 'icon ' . LGConstant::ACTION_UP;

	    $url = url(app()->controller->id . '/order/' . $albumModel->id . $actionParam);
	    $html .= $this->createAjaxButtonUpdateGridView($actionClassName, $url);
	} else {
	    $actionClassName = 'icon ' . LGConstant::ACTION_UP . ' disable';
	    $html .= CHtml::button('', array(
			'class' => $actionClassName,
	    ));
	}

	return $html;
    }

    public function createAjaxButtonUpdateGridView($className, $url) {
	return '<input class="' . $className . '" onclick="LGCMS.ajaxCallback(\'' . $url . '\')" name="yt2" type="button">';
    }

    /**
     * 
     * @param Album $albumModel
     * @return string	HTML string
     */
    public function getHtmlDownButtonForAlbum($albumModel) {
	$html = '';
	if ($albumModel->nextAlbumID != NULL) {
	    $actionParam = '?action=' . $albumModel->nextAlbumID;
	    $actionClassName = 'icon ' . LGConstant::ACTION_DOWN;

	    $url = url('/' . app()->controller->id . '/order/' . $albumModel->id . $actionParam);
	    $html .= $this->createAjaxButtonUpdateGridView($actionClassName, $url);
	} else {
	    $actionClassName = 'icon ' . LGConstant::ACTION_DOWN . ' disable';
	    $html .= CHtml::button('', array(
			'class' => $actionClassName,
	    ));
	}

	return $html;
    }

    /**
     * 
     * @param Photo $photoModel
     * @return string HTML string
     */
    public function getHtmlUpButtonForPhoto($photoModel) {

	$html = '';
	if ($photoModel->previousPhotoID != NULL) {
	    $actionParam = '?action=' . $photoModel->previousPhotoID;
	    $actionClassName = 'icon ' . LGConstant::ACTION_UP;

	    $url = url(app()->controller->id . '/orderPhoto/' . $photoModel->id . $actionParam);
	    $html .= $this->createAjaxButtonUpdateGridView($actionClassName, $url);
	} else {
	    $actionClassName = 'icon ' . LGConstant::ACTION_UP . ' disable';
	    $html .= CHtml::button('', array(
			'class' => $actionClassName,
	    ));
	}

	return $html;
    }

    /**
     * 
     * @param Photo $photoModel
     * @return string HTML string
     */
    public function getHtmlDownButtonForPhoto($photoModel) {
	$html = '';
	if ($photoModel->nextPhotoID != NULL) {
	    $actionParam = '?action=' . $photoModel->nextPhotoID;
	    $actionClassName = 'icon ' . LGConstant::ACTION_DOWN;

	    $url = url('/' . app()->controller->id . '/orderPhoto/' . $photoModel->id . $actionParam);
	    $html .= $this->createAjaxButtonUpdateGridView($actionClassName, $url);
	} else {
	    $actionClassName = 'icon ' . LGConstant::ACTION_DOWN . ' disable';
	    $html .= CHtml::button('', array(
			'class' => $actionClassName,
	    ));
	}

	return $html;
    }

    public function actionOrder($id, $action) {

	if ($id == NULL || $action == NULL) {
	    //TODO : handle
	} else {
	    $albumFrom = Album::model()->findByPk($id);
	    $albumTo = Album::model()->findByPk($action);
	    if ($albumFrom == NULL || $albumTo == NULL) {
		throw new CHttpException(404, Yii::t('messages', '404'));
	    }

	    if ($albumFrom->display_order == $albumTo->display_order) {
		$albumTo->display_order++;
	    }

	    $temp = $albumFrom->display_order;
	    $albumFrom->display_order = $albumTo->display_order;
	    $albumTo->display_order = $temp;

	    if (!$albumFrom->saveAttributes(array('display_order'))) {
		throw new CHttpException(500, Yii::t('messages', '500'));
	    }

	    if (!$albumTo->saveAttributes(array('display_order'))) {
		throw new CHttpException(500, Yii::t('messages', '500'));
	    }
	}
    }

    public function actionOrderPhoto($id, $action) {

	if ($id == NULL || $action == NULL) {
	    //TODO : handle
	} else {
	    $photoFrom = Photo::model()->findByPk($id);
	    $photoTo = Photo::model()->findByPk($action);
	    if ($photoFrom == NULL || $photoTo == NULL) {
		throw new CHttpException(404, Yii::t('messages', '404'));
	    }

	    if ($photoFrom->display_order == $photoTo->display_order) {
		$photoTo->display_order++;
	    }

	    $temp = $photoFrom->display_order;
	    $photoFrom->display_order = $photoTo->display_order;
	    $photoTo->display_order = $temp;

	    if (!$photoFrom->saveAttributes(array('display_order'))) {
		throw new CHttpException(500, Yii::t('messages', '500'));
	    }

	    if (!$photoTo->saveAttributes(array('display_order'))) {
		throw new CHttpException(500, Yii::t('messages', '500'));
	    }
	}
    }

    /**
     * 
     * @param Photo $photo
     * @return string HTML string
     */
    public function updatePhotoButtonHtml($photo, $diaglogWidth, $diaglogHeight) {
	return CHtml::link($photo->name, url('gallery/updatePhoto/', array('id' => $photo->id)), array(
		    'class' => 'update-file-dialog-open-link',
		    'data-update-dialog-title' => 'Edit Photo',
		    'dialog-height' => $diaglogHeight,
		    'dialog-width' => $diaglogWidth
	));
    }

}
